// import { MongoClient } from "mongodb";

// if (!process.env.MONGODB_URI) {
//     throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
// }

// const uri = process.env.MONGODB_URI;
// const options = {};

// let client: MongoClient;

// if (process.env.NODE_ENV === "development") {
//     // In development mode, use a global variable so that the value
//     // is preserved across module reloads caused by HMR (Hot Module Replacement).
//     let globalWithMongo = global as typeof globalThis & {
//         _mongoClient?: MongoClient;
//     };

//     if (!globalWithMongo._mongoClient) {
//         globalWithMongo._mongoClient = new MongoClient(uri, options);
//     }
//     client = globalWithMongo._mongoClient;
// } else {
//     // In production mode, it's best to not use a global variable.
//     client = new MongoClient(uri, options);
// }

// // Export a module-scoped MongoClient. By doing this in a
// // separate module, the client can be shared across functions.

// export const connectToDatabase = async () => {
//     try {
//         await client.connect();
//         console.log('Connected to MongoDB');
//         return client;
//     } catch (err) {
//         console.error('Error connecting to MongoDB', err);
//         throw err;
//     }
// };

// export const closeDatabaseConnection = async () => {
//     if (client) {
//         await client.close();
//         console.log('Disconnected from MongoDB');
//     }
// };
// export default client

import mongoose from "mongoose";
let db:any 
export const connectToDatabase = async () => {
    try { 
        const url: any = process.env.MONGODB_URI; 
        
        if (!db) {
            db = await mongoose.connect(url);
            console.log('MongoDB connected...');
        }else{
            console.log('MongoDB already connected...');
        }
    } catch (err: any) {
        console.error(err,'-----错误-----');
        process.exit(1);
    }
};

